package com.mkirl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.widget.Toast;


public class ServerCommunicator {
	
	String rootURL = "http://10.mkirlgame.appspot.com/";
	Context mContext;
	int ascore, bscore, treasurestoplace;
	//final ShowLocalGamesTask showLocalGamesTask = new ShowLocalGamesTask();
	
	//overloaded constructor to work with other server addresses
	public ServerCommunicator(Context m, String rootAddress) {
		mContext = m;
		rootURL = rootAddress;
	}
	
	//default constructor
	public ServerCommunicator(Context m) {
		mContext = m;
	}
	
	/* NOT IN USE
	public void showLocalGames(GeoPoint p) {
		showLocalGamesTask.execute(p);
	}
	*/
	
	
	// OUT OF USE
	/*
	public void sendCommand(final String s, final Player player) {
		HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(rootURL+"/GID/update?gameID="+player.getGameID());
	    
	    try{
	    	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        	nameValuePairs.add(new BasicNameValuePair("command", s));
        	nameValuePairs.add(new BasicNameValuePair("playerID", player.getPlayerID()));
	        nameValuePairs.add(new BasicNameValuePair("latitude", "" + player.getLatitude()));
	        nameValuePairs.add(new BasicNameValuePair("longitude", "" + player.getLongitude()));
        	nameValuePairs.add(new BasicNameValuePair("team", player.getTeam()));
	        nameValuePairs.add(new BasicNameValuePair("userClass", player.getUserClass()));
        	nameValuePairs.add(new BasicNameValuePair("heading", ""+player.getHeading()));
	        nameValuePairs.add(new BasicNameValuePair("gpsAccuracy", ""+player.getGPSAccuracy()));
        	httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        	// Execute HTTP Post Request
        	HttpResponse response = httpclient.execute(httppost);            
        	
        	if(response!=null){
        		StringBuffer out = new StringBuffer();
        	    byte[] b = new byte[4096];
        	    InputStream is = response.getEntity().getContent();
        	    for (int n; (n = is.read(b)) != -1;) {
        	        out.append(new String(b, 0, n));
        	    }
        	    String responseAsStr = out.toString();
        		     		
                
        		//DEBUG PURPOSES
        		Toast.makeText(mContext, responseAsStr, Toast.LENGTH_SHORT).show();
            }
        	
        }
	    catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } 
	    catch (IOException e) {
	        // TODO Auto-generated catch block
	    }
	}
	
	*/
	
	public void postPlayerToServer(final Player player) {
    	//this should edit the inGame variable and tickerTape if it returns false
		
		Thread t = new Thread() {
		public void run() {
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(rootURL+"/update?gameID="+player.getGameID());
		    String responseAsStr = "";
		    try {
		    	//Toast.makeText(mContext, "In try block", Toast.LENGTH_SHORT).show();
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		        	nameValuePairs.add(new BasicNameValuePair("playerID", player.getPlayerID()));
			        nameValuePairs.add(new BasicNameValuePair("latitude", "" + player.getLatitude()));
			        nameValuePairs.add(new BasicNameValuePair("longitude", "" + player.getLongitude()));
		        	nameValuePairs.add(new BasicNameValuePair("team", player.getTeam()));
			        nameValuePairs.add(new BasicNameValuePair("userClass", player.getUserClass()));
		        	nameValuePairs.add(new BasicNameValuePair("heading", ""+player.getHeading()));
			        nameValuePairs.add(new BasicNameValuePair("gpsAccuracy", ""+player.getGPSAccuracy()));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        //Toast.makeText(mContext, "executing Post", Toast.LENGTH_SHORT).show();
	        
		    	if(response!=null){
		    		StringBuffer out = new StringBuffer();
		    	    byte[] b = new byte[4096];
		    	    InputStream is = response.getEntity().getContent();
		    	    for (int n; (n = is.read(b)) != -1;) {
		    	        out.append(new String(b, 0, n));
		    	    }
		    	    responseAsStr = out.toString();
		        	String[] responses = responseAsStr.split(" ");
		        	ascore = Integer.parseInt(responses[0]);
		        	bscore = Integer.parseInt(responses[1]);
		        	treasurestoplace = Integer.parseInt(responses[2]);
		        	
		    	}
		    } 
		catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    } 
		catch (IOException e) {
	        // TODO Auto-generated catch block
	    }

		((MKIRL)mContext).updateHandler.post(updateRunnable);
	}
	};
	t.start();
	
	
   }
	
	public Runnable updateRunnable = new Runnable() {
		public void run() {
			((MKIRL)mContext).updateGameState(ascore, bscore, treasurestoplace);
		}
		
	};

}//end outter class ServerCommunicator